import { Component, OnInit, ViewChild, Output, EventEmitter, Inject, forwardRef, ChangeDetectorRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { HomepagePopGridComponent } from '../homepage-pop-grid/homepage-pop-grid.component';
import { SelectImageAddComponent } from './select-image-add/select-image-add.component'
import { FileUploader } from '../../../../../lib/ng2-file-upload';
import { path } from '../../../../path.config';
import { masterService } from '../../../../../lib/master.service';
import { saveVarService } from '../../../../../lib/saveVar.service';
import { AppComponent } from '../../../../app.component';

import * as $ from 'jquery';

@Component({
    selector: 'app-homepage-pop-add',
    templateUrl: './homepage-pop-add.component.html',
    styleUrls: ['./homepage-pop-add.component.css'],
    providers: [forwardRef(() => HomepagePopGridComponent), saveVarService, forwardRef(() => AppComponent)]
})
export class HomepagePopAddComponent implements OnInit {
    @ViewChild('newHomepage') public newHomepage: ModalDirective;
    @ViewChild('homePageSelectImage') public homePageSelectImage: SelectImageAddComponent;

    @Output() homePageAdd = new EventEmitter<any>();
    // 上传图片
    private addImgItem = path.imagesUpload.apiUrl;
    // 添加新列表项
    private addListItem = path.pageManagement.homepagePopup.addHomePageListItem;
    // 上传图片后获取图片id
    private getImgId = path.imagesUpload.getImgId;
    // 首页弹窗跳转类型
    private getlatformType = path.pageManagement.homepagePopup.getlatformType;

    public add: any = {
        imageId: '',
        pageName: '',
        linkUrl: '',
        homePageType: 2,
        redirectingType: '-1',
        redirectingValue: ''
    }

    public redirectingOptions:any;
    public uploadPic = {};
    public addCheckVar = false;

    constructor(private _masterService: masterService,
        private cdRef: ChangeDetectorRef,
        public _saveVar: saveVarService,
        @Inject(forwardRef(() => HomepagePopGridComponent)) private homePageGrid: HomepagePopGridComponent,
        @Inject(forwardRef(() => AppComponent)) public app: AppComponent) { }

    ngOnInit() {
        this._masterService
            .getData(this.getlatformType)
            .subscribe((res)=> {
                if(res.statusCode == 200) {
                    this.redirectingOptions = res.data.items;
                    this.cdRef.detectChanges();
                } else {
                    this.app.toastError('错误信息： ' + res.errorMessage);
                }
            })
    }

    public uploader: FileUploader = new FileUploader({
        url: this.addImgItem,
        method: 'post',
        itemAlias: 'uploadedFile'
    });

    // 本地上传文件后触发
    selectedFileOnChanged(event: any) {
        let $this = this;
        let thisItem = $this.uploader.queue[0] = $this.uploader.queue[$this.uploader.queue.length - 1];
        let reader = new FileReader();
        reader.readAsDataURL(thisItem.some);
        reader.onload = function (e) {
            thisItem.src = this.result as string;
            var img = new Image();
            img.src = thisItem.src;
            img.onload = function () {
                // 存图片的分辨率
                thisItem.resolution = img.width + '*' + img.height;
            }
        }
        this.cdRef.detectChanges();
    }

    // 上传图片
    uploadFile(thisItem) {
        let that = this;
        if (thisItem == undefined) {
            this.app.toastWarning('请上传或选择图片！');
            return;
        }

        thisItem.withCredentials = false;
        // 成功回调
        thisItem.onSuccess = function (response, status, headers) {
            // 上传文件成功
            if (status == 200) {
                // 上传文件后获取服务器返回的数据
                let tempRes = JSON.parse(response);
                that.uploadPic = {
                    imageName: thisItem.some.name,
                    imageUrl: tempRes.data.url[0],
                    extension: thisItem.some.type.split('/')[thisItem.some.type.split('/').length - 1],
                    imageSize: thisItem.some.size + 'B',
                    resolution: thisItem.resolution
                }
                that.app.toastSuccess('上传成功！');
                that._masterService
                    .postData(that.getImgId, that.uploadPic)
                    .subscribe((res) => {
                        if (res.statusCode == 200) {
                            that._saveVar.homeUpAddPicId = res.data;
                            that.add.imageUrl = tempRes.data.url[0];
                            that.uploader.queue = [];
                            that.cdRef.detectChanges();
                        } else {
                            that.app.toastError('错误信息: ' + res.errorMessage);
                        }
                    })
            } else {
                // 上传文件后获取服务器返回的数据错误
                that.app.toastError('错误信息: ' + response.errorMessage);
            }
        };

        thisItem.onError = function (response, status, headers) {
            // 错误回调
            that.app.toastError('错误信息: ' + response.errorMessage);
        };
        thisItem.upload(); // 开始上传
    }

    openSelectImageModal() {
        this.homePageSelectImage.openAddModal();
    }

    // 新建首页弹窗
    public addHomepage() {
        this.add.imageId = this._saveVar.homeUpAddPicId;
        if (!this.add.imageId) {
            this.app.toastWarning('请上传图片！');
            return;
        } else if (!this.add.pageName) {
            this.app.toastWarning('请填写名称！');
            return;
        } else if (!this.add.homePageType) {
            this.app.toastWarning('请填写弹窗类型！');
            return;
        }

        this._masterService
            .postData(this.addListItem, this.add)
            .subscribe((res) => {
                this.newHomepage.hide();
                if (res.statusCode == 200) {
                    this.app.toastSuccess('添加成功！');
                    this.homePageAdd.emit();
                } else {
                    this.app.toastError('错误信息: ' + res.errorMessage);
                }
                this.add = {
                    imageId: '',
                    pageName: '',
                    linkUrl: '',
                    homePageType: 2
                };
                $('#homePage-uploader').val('');
                this.uploader.queue = [];
            })
    }

    // 选择完的图片传出给add模态框
    public SelectImage(url) {
        this.add.imageUrl = url;
    }

    closeModal() {
        this.newHomepage.hide();
        this.add = {
            imageId: '',
            pageName: '',
            linkUrl: '',
            homePageType: 2
        };
        $('#homePage-uploader').val('');
        this.uploader.queue = [];
    }
}
